<template>
  <div class="document-conversion-tool">
    <div class="header-container">
      <router-link to="/" class="back-btn">返回首页</router-link>
      <h1>文档转换工具</h1>
    </div>
    <div class="conversion-tabs">
      <button
        :class="{ 'active': activeTab === 'text' }"
        @click="activeTab = 'text'"
      >
        文本转换
      </button>
      <button
        :class="{ 'active': activeTab === 'word' }"
        @click="activeTab = 'word'"
      >
        Word转PDF
      </button>
      <button
        :class="{ 'active': activeTab === 'image' }"
        @click="activeTab = 'image'"
      >
        图片转PDF
      </button>
      <button
        :class="{ 'active': activeTab === 'powerpoint' }"
        @click="activeTab = 'powerpoint'"
      >
        PPT转PDF
      </button>
    </div>

    <div class="conversion-form" v-if="activeTab === 'text'">
      <div class="form-group">
        <label for="documentTitle">文档标题</label>
        <input
          type="text"
          id="documentTitle"
          v-model="documentTitle"
          placeholder="请输入文档标题"
        >
      </div>

      <div class="form-group">
        <label>转换格式</label>
        <div class="format-options">
          <label class="format-option">
            <input
              type="radio"
              value="ppt"
              v-model="selectedFormat"
            >
            PPT
          </label>
          <label class="format-option">
            <input
              type="radio"
              value="word"
              v-model="selectedFormat"
            >
            Word
          </label>
          <!-- PDF转换功能已禁用 -->
          <label class="format-option" style="opacity: 0.5; cursor: not-allowed;">
            <input
              type="radio"
              value="pdf"
              v-model="selectedFormat"
              disabled
            >
            PDF (已禁用)
          </label>
        </div>
      </div>

      <div class="form-group">
        <label for="modelResult">大模型结果</label>
        <textarea
          id="modelResult"
          v-model="modelResult"
          placeholder="请粘贴大模型返回的文本结果"
          rows="10"
        ></textarea>
      </div>

      <button
        class="convert-btn"
        @click="convertDocument"
        :disabled="isConverting"
      >
        {{ isConverting ? '转换中...' : '开始转换' }}
      </button>
    </div>

    <div class="conversion-form" v-if="activeTab === 'word'">
      <div class="form-group">
        <label for="wordFile">上传Word文档</label>
        <input
          type="file"
          id="wordFile"
          accept=".doc,.docx"
          @change="handleWordFileChange"
        >
        <div v-if="selectedWordFile" class="file-name">
          已选择: {{ selectedWordFile.name }}
        </div>
      </div>

      <button
        class="convert-btn"
        @click="convertWordToPdf"
        :disabled="isConverting || !selectedWordFile"
      >
        {{ isConverting ? '转换中...' : 'Word转PDF' }}
      </button>
    </div>

    <div class="conversion-form" v-if="activeTab === 'image'">
      <div class="form-group">
        <label for="imageFiles">上传图片</label>
        <input
          type="file"
          id="imageFiles"
          accept=".jpg,.jpeg,.png,.gif"
          multiple
          @change="handleImageFilesChange"
        >
        <div v-if="selectedImageFiles.length > 0" class="file-list">
          <p>已选择 {{ selectedImageFiles.length }} 张图片:</p>
          <ul>
            <li v-for="(file, index) in selectedImageFiles" :key="index">
              {{ file.name }}
              <button @click="removeImageFile(index)">移除</button>
            </li>
          </ul>
        </div>
      </div>

      <button
        class="convert-btn"
        @click="convertImagesToPdf"
        :disabled="isConverting || selectedImageFiles.length === 0"
      >
        {{ isConverting ? '转换中...' : '图片转PDF' }}
      </button>
    </div>

    <div class="conversion-form" v-if="activeTab === 'powerpoint'">
      <div class="form-group">
        <label for="powerpointFile">上传PPT/PPTX文档</label>
        <input
          type="file"
          id="powerpointFile"
          accept=".ppt,.pptx"
          @change="handlePowerpointFileChange"
        >
        <div v-if="selectedPowerpointFile" class="file-name">
          已选择: {{ selectedPowerpointFile.name }}
        </div>
      </div>

      <button
        class="convert-btn"
        @click="convertPowerpointToPdf"
        :disabled="isConverting || !selectedPowerpointFile"
      >
        {{ isConverting ? '转换中...' : 'PPT转PDF' }}
      </button>
    </div>

    <div v-if="conversionStatus" class="status-message">
      {{ conversionStatus }}
    </div>
  </div>
</template>

<script>
import { downloadFile, formatDate } from '../../documentConverter/utils';
import axios from 'axios';
// 尝试使用绝对路径导入
import config from '@/config.js';

export default {
  name: 'DocumentConversionTool',
  data() {
    return {
      activeTab: 'text', // text, word, image, powerpoint
      documentTitle: '大模型结果报告',
      selectedFormat: 'word', // 默认选择Word格式，因为PDF已禁用
      modelResult: '',
      isConverting: false,
      conversionStatus: '',
      selectedWordFile: null,
      selectedImageFiles: [],
      selectedPowerpointFile: null
    };
  },
  methods: {
    // 文本转换为文档
    async convertDocument() {
      // 验证输入
      if (!this.modelResult.trim()) {
        this.conversionStatus = '请输入大模型结果';
        return;
      }

      // 重置状态
      this.conversionStatus = '';
      this.isConverting = true;

      try {
        // 使用文本内容
        const data = this.modelResult;

        this.conversionStatus = '开始转换文档...';

        // 创建FormData对象
        const formData = new FormData();
        formData.append('title', this.documentTitle);
        formData.append('format', this.selectedFormat);
        formData.append('content', data);

        // 调用后端API
        const response = await axios.post(`${config.api.baseUrl}/api/document/text-convert`, formData,
          { responseType: 'blob' });

        // 处理响应
        const blob = response.data;
        let filename = `${this.documentTitle}_${formatDate(new Date())}`;
        switch (this.selectedFormat) {
          case 'ppt':
            filename += '.pptx';
            break;
          case 'word':
            filename += '.docx';
            break;
          case 'pdf':
          default:
            filename += '.pdf';
        }

        // 下载文件
        downloadFile(blob, filename);

        this.conversionStatus = '转换成功！文件已开始下载';
      } catch (error) {
        console.error('文档转换失败:', error);
        this.conversionStatus = `转换失败: ${error.message || '未知错误'}`;
      } finally {
        // 确保无论成功失败，按钮都能恢复可点击状态
        this.isConverting = false;
      }
    },

    // 处理Word文件选择
    handleWordFileChange(event) {
      if (event.target.files && event.target.files[0]) {
        this.selectedWordFile = event.target.files[0];
      }
    },

    // 处理图片文件选择
    handleImageFilesChange(event) {
      if (event.target.files && event.target.files.length > 0) {
        this.selectedImageFiles = [...event.target.files];
      }
    },

    // 移除选中的图片
    removeImageFile(index) {
      this.selectedImageFiles.splice(index, 1);
    },

    // 处理PPT文件选择
    handlePowerpointFileChange(event) {
      if (event.target.files && event.target.files[0]) {
        this.selectedPowerpointFile = event.target.files[0];
      }
    },

    // PPT转PDF
    async convertPowerpointToPdf() {
      if (!this.selectedPowerpointFile) {
        this.conversionStatus = '请选择PPT/PPTX文档';
        return;
      }

      // 重置状态
      this.conversionStatus = '';
      this.isConverting = true;

      try {
        this.conversionStatus = '开始上传PPT文档...';

        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', this.selectedPowerpointFile);

        // 调用后端API
        const response = await axios.post(`${config.api.baseUrl}/api/document/convert-powerpoint-to-pdf`, formData,
          { responseType: 'blob' });

        // 处理响应
        const blob = response.data;
        const filename = this.selectedPowerpointFile.name.replace(/\.(ppt|pptx)$/i, '.pdf');

        // 下载文件
        downloadFile(blob, filename);

        this.conversionStatus = '转换成功！文件已开始下载';
      } catch (error) {
        console.error('PPT转PDF失败:', error);
        this.conversionStatus = `转换失败: ${error.message || '未知错误'}`;
      } finally {
        // 确保无论成功失败，按钮都能恢复可点击状态
        this.isConverting = false;
      }
    },

    // Word转PDF
    async convertWordToPdf() {
      if (!this.selectedWordFile) {
        this.conversionStatus = '请选择Word文档';
        return;
      }

      // 重置状态
      this.conversionStatus = '';
      this.isConverting = true;

      try {
        this.conversionStatus = '开始上传Word文档...';

        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', this.selectedWordFile);

        // 调用后端API
        const response = await axios.post(`${config.api.baseUrl}/api/document/word-to-pdf`, formData,
          { responseType: 'blob' });

        // 处理响应
        const blob = response.data;
        const filename = this.selectedWordFile.name.replace(/\.(doc|docx)$/i, '.pdf');

        // 下载文件
        downloadFile(blob, filename);

        this.conversionStatus = '转换成功！文件已开始下载';
      } catch (error) {
        console.error('Word转PDF失败:', error);
        this.conversionStatus = `转换失败: ${error.message || '未知错误'}`;
      } finally {
        // 确保无论成功失败，按钮都能恢复可点击状态
        this.isConverting = false;
      }
    },

    // 图片转PDF
    async convertImagesToPdf() {
      if (this.selectedImageFiles.length === 0) {
        this.conversionStatus = '请选择图片文件';
        return;
      }

      // 重置状态
      this.conversionStatus = '';
      this.isConverting = true;

      try {
        this.conversionStatus = '开始上传图片...';

        // 创建FormData对象
        const formData = new FormData();
        this.selectedImageFiles.forEach(file => {
          formData.append('files', file);
        });

        // 调用后端API
        const response = await axios.post(`${config.api.baseUrl}/api/document/images-to-pdf`, formData,
          { responseType: 'blob' });

        // 处理响应
        const blob = response.data;
        const filename = `images_${formatDate(new Date())}.pdf`;

        // 下载文件
        downloadFile(blob, filename);

        this.conversionStatus = '转换成功！文件已开始下载';
      } catch (error) {
        console.error('图片转PDF失败:', error);
        this.conversionStatus = `转换失败: ${error.message || '未知错误'}`;
      } finally {
        // 确保无论成功失败，按钮都能恢复可点击状态
        this.isConverting = false;
      }
    }
  }
};
</script>

<style scoped>
.document-conversion-tool {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  background-color: #3498db;
  color: white;
  text-decoration: none;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  transition: background-color 0.3s;
}

.back-btn:hover {
  background-color: #2980b9;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.conversion-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

input[type="text"],
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

textarea {
  resize: vertical;
}

.format-options {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.format-option {
  display: flex;
  align-items: center;
  gap: 5px;
}

.convert-btn {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  width: 100%;
  transition: background-color 0.3s;
}

.convert-btn:hover:not(:disabled) {
  background-color: #3aa876;
}

.convert-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.status-message {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
  font-weight: bold;
}
</style>